
from flask import Blueprint, request, jsonify, Response, stream_with_context
from langchain_core.messages import HumanMessage, AIMessage
import json
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

# 导入主应用中的模型和会话历史
from app import chat_model, session_histories

chat_bp = Blueprint('chat', __name__)

@chat_bp.route('/chat', methods=['POST'])
def chat():
    print("---------chat_messages.py")
    """处理聊天请求"""
    try:
        data = request.json
        user_input = data.get('message')
        session_id = data.get('session_id', 'default')

        if not user_input:
            return jsonify({'error': '消息不能为空'}), 400

        # 获取或创建会话历史
        if session_id not in session_histories:
            session_histories[session_id] = []

        # 添加用户消息到历史
        session_histories[session_id].append(HumanMessage(content=user_input))

        # 构建消息历史
        messages = session_histories[session_id][-10:]  # 限制历史消息数量

        # 调用模型并流式输出
        def generate():
            try:
                full_response = ""
                for chunk in chat_model.stream(messages):
                    full_response += chunk.content
                    # 以 SSE 格式发送数据
                    yield f"data: {json.dumps({'content': chunk.content})}\n\n"

                # 将完整回复添加到历史记录
                session_histories[session_id].append(AIMessage(content=full_response))

                # 发送结束信号
                yield "data: [DONE]\n\n"
            except Exception as e:
                yield f"data: {json.dumps({'error': str(e)})}\n\n"

        return Response(stream_with_context(generate()), content_type='text/event-stream')

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@chat_bp.route('/clear_history', methods=['POST'])
def clear_history():
    """清除会话历史"""
    try:
        session_id = request.json.get('session_id', 'default')
        if session_id in session_histories:
            session_histories[session_id] = []
        return jsonify({'message': '历史记录已清除'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500